// pages/myself/feedback-zone/feedbackZone.js
const { validate } = require('../../../utils/validator.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: app.globalData.userInfo,
    isLoadMore: false,
    isNotdate: false,
    customerList: [],
    type: 'news',
    keyword: '',
    page: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    rules: {
      keyword: [
        { validator(rule, value, callback) {
            const reg = /^[a-zA-Z\u4e00-\u9fa5]*$/
            if (!reg.test(value)) {
              callback(new Error('姓名需为2-10位中文或英文字符'))
            } else {
              callback()
            }
          } },
      ],
    },
  },
  swipeCheckX:0, //激活检测滑动的阈值
  swipeCheckState:0, //0未激活 1激活
  maxMoveLeft:75, //消息列表项最大左滑距离
  correctMoveLeft:75, //显示菜单时的左滑距离
  thresholdMoveLeft: 55,//左滑阈值，超过则显示菜单
  lastShowMsgId:'', //记录上次显示菜单的消息id
  moveX:0,  //记录平移距离
  showState:0, //0 未显示菜单 1显示菜单
  touchStartState:0, // 开始触摸时的状态 0 未显示菜单 1 显示菜单
  swipeDirection:0, //是否触发水平滑动 0:未触发 1:触发水平滑动 2:触发垂直滑动

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let userInfo = { ...app.globalData.userInfo }
    this.setData({ info: userInfo })
    this.setData({
      'page.currentPage': 1
    })
    this.getCustomerList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  toFeedback () {
      wx.navigateTo({
        url: '/myself/pages/create-feedback/createFeedback',
      })
  },
  loadMore () {
    console.log('加载了更多')
    const { page, customerList } = this.data
    if (page.total > customerList.length) {
      this.setData({
        'page.currentPage': page.currentPage + 1,
        'isLoadMore': true
      })
      this.getCustomerList()
    }
  },
  getCustomerList: function () {
    let { page, keyword, customerList } = this.data
    const params = {
      currentPage: page.currentPage,
      pageSize: page.pageSize,
      keyword
    }
    let Url = this.data.info.roleCode === 'admin-exclusive' || this.data.info.roleCode === 'admin-nonExclusive' || this.data.info.roleCode === 'admin-promoter' || this.data.info.roleCode === 'admin-admin' ? 'vx_feedback_searchReplyMsgForAdmin' : 'vx_feedback_searchReplyMsgForStudent'
    app.api.post({
      url: Url,
      data: params
    }).then(res => {
      let arr = []
      if (res.list.length > 0) {
        arr = res.list
        if (this.data.isLoadMore) {
          console.log('执行加载')
          customerList.push(...arr)
        } else {
          console.log('执行加载2')
          customerList = arr
        }
        console.log(customerList)
        this.setData({
          customerList,
          isLoadMore: false,
          isNotdate: false,
          'page.total': Number(res.total)
        })
      } else {
        this.setData({
          customerList: [],
          isNotdate: true
        })
      }
    })
  },
  changeType: function (e) {
    const { type } = e.currentTarget.dataset
    this.setData({ type })
  },
  input: function (e) {
    this.setData({
      keyword: e.detail.value.replace(/\s+/g, ''),
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      customerList: []
    })
    this.getCustomerList()
  },
  ontouchstart: function(e) {
    console.log('开始')
    if (this.showState === 1) {
      this.touchStartState = 1;
      this.showState = 0;
      this.moveX = 0;
      this.translateXMsgItem(this.lastShowMsgId, 0, 200);
      this.lastShowMsgId = "";
      return;
    }
    this.firstTouchX = e.touches[0].clientX;
    this.firstTouchY = e.touches[0].clientY;
    if (this.firstTouchX > this.swipeCheckX) {
      this.swipeCheckState = 1;
    }
    this.lastMoveTime = e.timeStamp;
  },
  ontouchmove: function(e) {
    console.log('移动')
    if (this.swipeCheckState === 0) {
      return;
    }
    //当开始触摸时有菜单显示时，不处理滑动操作
    if (this.touchStartState === 1) {
      return;
    }
    var moveX = e.touches[0].clientX - this.firstTouchX;
    var moveY = e.touches[0].clientY - this.firstTouchY;
    //已触发垂直滑动，由scroll-view处理滑动操作
    if (this.swipeDirection === 2) {
      return;
    }
    //未触发滑动方向
    if (this.swipeDirection === 0) {
      console.log(Math.abs(moveY));
      //触发垂直操作
      if (Math.abs(moveY) > 4) {
        this.swipeDirection = 2;

        return;
      }
      //触发水平操作
      if (Math.abs(moveX) > 4) {
        this.swipeDirection = 1;
        this.setData({scrollY:false});
      }
      else {
        return;
      }
        
    }
    //禁用垂直滚动
    // if (this.data.scrollY) {
    //   this.setData({scrollY:false});
    // }

    this.lastMoveTime = e.timeStamp;
    //处理边界情况
    if (moveX > 0) {
      moveX = 0;
    }
    //检测最大左滑距离
    if (moveX < -this.maxMoveLeft) {
      moveX = -this.maxMoveLeft;
    }
    this.moveX = moveX;
    this.translateXMsgItem(e.currentTarget.id, moveX, 0);
  },
  ontouchend: function(e) {
    console.log('结束')
    this.swipeCheckState = 0;
    var swipeDirection = this.swipeDirection;
    this.swipeDirection = 0;
    if (this.touchStartState === 1) {
      this.touchStartState = 0;
      this.setData({scrollY:true});
      return;
    } 
    //垂直滚动，忽略
    if (swipeDirection !== 1) {
      return;
    }
    if (this.moveX === 0) {
      this.showState = 0;
      //不显示菜单状态下,激活垂直滚动
      this.setData({scrollY:true});
      return;
    }
    if (this.moveX === this.correctMoveLeft) {
      this.showState = 1;
      this.lastShowMsgId = e.currentTarget.id;
      return;
    }  
    if (this.moveX < -this.thresholdMoveLeft) {
      this.moveX = -this.correctMoveLeft;
      this.showState = 1;
      this.lastShowMsgId = e.currentTarget.id;
    }
    else {
      this.moveX = 0;
      this.showState = 0;
      //不显示菜单,激活垂直滚动
      this.setData({scrollY:true});
    }
    this.translateXMsgItem(e.currentTarget.id, this.moveX, 500);
    //this.translateXMsgItem(e.currentTarget.id, 0, 0);
  },
  onDeleteMsgTap: function(e) {
    console.log(e)
    this.deleteMsgItem(e);
  },
  deleteMsgItem: function(e) {
    var animation = wx.createAnimation({duration:200});
    animation.height(0).opacity(0).step();
    this.animationMsgWrapItem(e.currentTarget.id, animation);
    var s = this;
    setTimeout(function() {
      var id = e.currentTarget.id
      console.log(id)
      app.api.post({
        url: 'vx_feedback_deleteReplyMsg',
        data: {notifyId: id}
      }).then(res => {
        s.setData({
          page: {
            currentPage: 1,
            pageSize: 10,
            total: 0
          },
          customerList: []
        })
        console.log(4)
        s.getCustomerList()
      })
      }, 200);
    this.showState = 0;
    this.setData({scrollY:true});
  },
  translateXMsgItem: function(id, x, duration) {
    var animation = wx.createAnimation({duration:duration});
    animation.translateX(x).step();
    this.animationMsgItem(id, animation);
  },
  animationMsgItem: function(id, animation) {
    var index = this.getItemIndex(id);
    var param = {};
    var indexString = 'customerList[' + index + '].animation';
    param[indexString] = animation.export();
    this.setData(param);
  },
  animationMsgWrapItem: function(id, animation) {
    var index = this.getItemIndex(id);
    var param = {};
    var indexString = 'customerList[' + index + '].wrapAnimation';
    param[indexString] = animation.export();
    this.setData(param);
  },
  getItemIndex: function(id) {
    var msgList = this.data.customerList;
    console.log(msgList)
    for (var i = 0; i < msgList.length; i++) {
      if (msgList[i].notifyId === id) {
        return i;
      }
    }
    return -1;
  },
  goToDetail (e) {
    const { feedbackId, deletedFlag } = e.currentTarget.dataset.item
    if (deletedFlag === '1') {
      wx.showModal({
        content: '反馈已经被删除',
        showCancel: false,
        success () {
          
        }
      })
    } else {
      wx.navigateTo({
        url: `/myself/pages/feedback-detail/feedbackDetail?id=${feedbackId}`
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})